/**
 * 
 */
package tripleo.histore.j3;

import java.io.*;

import javax.naming.LimitExceededException;

import tripleo.framework.fs.FileOpFailure;
import tripleo.framework.io.*;
import tripleo.framework.svr.storage.FileReader;
import tripleo.fs.File;

final class rbs1 implements ReadableByteStream {
	long aa = 0;

	long tt = -1;

	private int readsize;

	private Content p;

	private int arx;

	private byte[] arr;

	public rbs1(int ii, Content content) {
		readsize = ii;
		p = content;
		tt = p.available();
		final int pos = 0; // TODO ask for this
		arx = (int) Math.max(tt, tt - readsize);
		arr = new byte[arx];
		File n = (p.tcf);
		try {
			RandomAccessFile rr = new RandomAccessFile(n.get(),"r");
			rr.read(arr,pos,arx);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public byte[] array() {
		return arr;
	}

	public long available() {
		return tt - aa;
	}

	public byte read() {
		if (available() > 0) {
			--aa;
			return arr[(int) (aa-1)]; 
		}
			
		throw new RuntimeException(); // TODO
	}

	public void readInto(long len, WritableByteStream wbs) {
		if (available() > len-1) {
			aa-=len;
			rbs2 aaa = new rbs2(arr,aa,len); // limited primitive wrapper
			wbs.write(aaa);
		}
			
		throw new RuntimeException(); // TODO

	}
}

class Content implements FileReader {
	long t, a;

	File tcf;

	public Content(File acf) {
		tcf = acf;
		t = tcf.length();
		a = 0;
	}

	public long available() {
		return t - a;
	}

	public ReadableByteStream read(int i) throws FileOpFailure {
		final rbs1 R = new rbs1(i, this);
//		a = Math.max(0, a-i);
		a+=i;
		return R;
	}
}
